import React, { useEffect, useState, useRef } from 'react'
import { Link, useHistory } from 'react-router-dom'

export default function NotFound() {
  // 方法一
  // const history = useHistory()
  // const [time, setTime] = useState(3)
  // useEffect(() => {
  //   let timer = setTimeout(() => {
  //     setTime(time - 1)
  //   }, 1000)
  //   if (time === 0) {
  //     clearTimeout(timer)
  //     history.push('/home')
  //   }
  // }, [history, time])
  // 方法二
  const [time, setTime] = useState(3)
  const history = useHistory()
  const tiemRef = useRef(-1)
  useEffect(() => {
    let timer = setInterval(() => {
      setTime((time) => {
        tiemRef.current = time - 1
        return time - 1
      })
      if (tiemRef.current === 0) {
        clearInterval(timer)
        history.push('/home')
      }
    }, 1000)
  }, [history])
  return (
    <div>
      <h1>对不起，你访问的内容不存在...</h1>
      <p>
        {time} 秒后，返回<Link to="/home">首页</Link>
      </p>
    </div>
  )
}
